/* Hello World Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include "esp_log.h"
#include "GNSS.h"
#include "IOT.h"
#include "LCD.h"
#include "Sensor.h"

char flag_1 = 0;


float jingdu=0,weidu=0;

static const char *TAG = "gps_demo";

#define TIME_ZONE (+8)   //Beijing Time
#define YEAR_BASE (2000) //date in GPS starts from 2000
gps_t *gps = NULL;

static void gps_event_handler(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
    switch (event_id) 
    {
        case GPS_UPDATE:
            gps = (gps_t *)event_data;
            /* print information parsed from GPS statements */
            ESP_LOGI(TAG, "%d/%d/%d %d:%d:%d => \r\n"
                    "\t\t\t\t\t\tlatitude   = %.05f°N\r\n"
                    "\t\t\t\t\t\tlongitude = %.05f°E\r\n"
                    "\t\t\t\t\t\taltitude   = %.02fm\r\n"
                    "\t\t\t\t\t\tspeed      = %fm/s",
                    gps->date.year + YEAR_BASE, gps->date.month, gps->date.day,
                    gps->tim.hour + TIME_ZONE, gps->tim.minute, gps->tim.second,
                    gps->latitude, gps->longitude, gps->altitude, gps->speed);
            break;
        case GPS_UNKNOWN:
            /* print unknown statements */
            ESP_LOGW(TAG, "Unknown statement:%s", (char *)event_data);
            break;
        default:
            break;
    }
}


void app_main(void)
{

   
    Uart2_NB_init();
    vTaskDelay(8000 / portTICK_PERIOD_MS);
    MQTT_Config();
    nmea_parser_config_t config = NMEA_PARSER_CONFIG_DEFAULT();
    nmea_parser_handle_t nmea_hdl = nmea_parser_init(&config);
    nmea_parser_add_handler(nmea_hdl, gps_event_handler, NULL);
    vTaskDelay(8000 / portTICK_PERIOD_MS);

    while(1)
    {
        if((gps->altitude>=1||gps->altitude<=-1)&& flag_1==0)
        {
            flag_1 = 1;

            //jingdu = gps->longitude;
            //weidu  = gps->latitude;
            nmea_parser_remove_handler(nmea_hdl, gps_event_handler);
            nmea_parser_deinit(nmea_hdl);
            Uart1_LCD_init();
        }

        Get_Sensor_Data();
        Process_MQTT_Data();
        /* 这里需要配置好MQTT 服务器后 再发送*/
        MQTT_Send_Data();

        vTaskDelay(8000 / portTICK_PERIOD_MS);
   }
}
